/**
 * 
 */
package com.py.credit.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.ServiceException;
import com.py.credit.constant.RecordStatusEnum;
import com.py.credit.constant.SubjectTypConstant;
import com.py.credit.dao.CreditReportDao;
import com.py.credit.dao.SSearchDao;
import com.py.credit.entity.Column;
import com.py.credit.entity.ColumnResult;
import com.py.credit.entity.ContentStyle;
import com.py.credit.entity.DataResult;
import com.py.credit.entity.TableResult;
import com.py.credit.service.ContentStyleService;
import com.py.credit.service.SSearchService;
import com.py.credit.utils.NumberUtils;
import com.py.credit.utils.SQLBuilder;
import com.py.credit.utils.elasticsearch.EsConstants;
import com.py.credit.utils.elasticsearch.EsPage;
import com.py.credit.utils.elasticsearch.EsQueryEntity;
import com.py.credit.utils.elasticsearch.EsQueryUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.rest.support.RestServiceResult;

/**
 * @author dd 共享查询服务
 */
@Service
public class SSearchServiceImpl implements SSearchService {
	@Autowired
	private SSearchDao sSearchDao;

	@Autowired
	private CreditReportDao creditReportDao;

	@Autowired
	private ContentStyleService contentStyleService;

	@Override
	public List<Map<String, Object>> getByConditionForPage(String kId, List<String> showColumns,
			String[] additionalColumns, String condition, Page page) {

		if (CollectionUtils.isEmpty(showColumns)) {

			throw new ServiceException("至少选择一列");

		}
		List<String> conditions = SQLBuilder.createConditionSql(condition);

		List<Map<String, Object>> tables = sSearchDao.selectByConditionForPage(kId, showColumns, additionalColumns,
				page, conditions);

		return tables;
	}

	@Override
	public List<Map<String, Object>> getTyshxydmTableListForPage(String condition, Page page) {

		return sSearchDao.selectTyshxydmTableListForPage(condition, page);
	}

	@Override
	public List<Map<String, Object>> getXyxxTableListForPage(String condition, Page page) {

		return sSearchDao.selectXyxxTableListForPage(condition, page);
	}

	@Override
	public Map<String, List<Map<String, Object>>> getXyxxDetail(String tybm, String type) {

		Map<String, List<Map<String, Object>>> result = new HashMap<String, List<Map<String, Object>>>(5);

		List<Map<String, Object>> jbxxList = null;

		List<Map<String, Object>> heimdDetailList = null;

		List<Map<String, Object>> hongmdDetailList = null;

		List<Map<String, Object>> xzcfDetailList = null;

		List<Map<String, Object>> xzxkDetailList = null;

		if ("FR".equals(type)) {

			jbxxList = sSearchDao.selectFrJbxx(tybm);

			heimdDetailList = sSearchDao.selectFrheimdDetail(tybm);

			hongmdDetailList = sSearchDao.selectFrHongmdDetail(tybm);

			xzcfDetailList = sSearchDao.selectFrxzcfDetail(tybm);

			xzxkDetailList = sSearchDao.selectFrxzxkDetail(tybm);

		} else if ("ZRR".equals(type)) {

			jbxxList = sSearchDao.selectZrrJbxx(tybm);

			heimdDetailList = sSearchDao.selectZrrheimdDetail(tybm);

			hongmdDetailList = sSearchDao.selectZrrHongmdDetail(tybm);

			xzcfDetailList = sSearchDao.selectZrrxzcfDetail(tybm);

			xzxkDetailList = sSearchDao.selectZrrxzxkDetail(tybm);

		}

		result.put("basicInfo", jbxxList);
		result.put("blackList", heimdDetailList);
		result.put("redList", hongmdDetailList);
		result.put("penaltyList", xzcfDetailList);
		result.put("licenseList", xzxkDetailList);

		return result;
	}

	@Override
	public List<Map<String, Object>> getSgsXxTableListByTypeForPage(String condition, Page page, String type) {

		if ("XK".equals(type)) {

			return sSearchDao.selectXzxkTableListForPage(condition, page);

		} else if ("CF".equals(type)) {

			return sSearchDao.selectXzcfTableListForPage(condition, page);

		} else {

			return new ArrayList<Map<String, Object>>();
		}

	}

	@Override
	public Map<String, List<Map<String, Object>>> getSgsXxDetail(String type, String name) {

		Map<String, List<Map<String, Object>>> result = new HashMap<String, List<Map<String, Object>>>(2);

		List<Map<String, Object>> xzcfDetailList = null;

		List<Map<String, Object>> xzxkDetailList = null;

		if ("FR".equals(type)) {

			xzcfDetailList = sSearchDao.selectFrxzcfDetailByName(name);

			xzxkDetailList = sSearchDao.selectFrxzxkDetailByName(name);

		} else if ("ZRR".equals(type)) {

			xzcfDetailList = sSearchDao.selectZrrxzcfDetailByName(name);

			xzxkDetailList = sSearchDao.selectZrrxzxkDetailByName(name);
		}

		result.put("penaltyList", xzcfDetailList);
		result.put("licenseList", xzxkDetailList);

		return result;
	}

	@Override
	public List<Map<String, String>> getKeyWords(String kId, String input) {

		List<Map<String, String>> selectUniqueAKeyWords = null;

		if ("100000".equals(kId)) {

			selectUniqueAKeyWords = sSearchDao.selectUniqueAKeyWords(kId, input);

		} else if ("100001".equals(kId)) {

			selectUniqueAKeyWords = sSearchDao.selectUniqueBKeyWords(kId, input);

			// 身份证脱敏

			if (!CollectionUtils.isEmpty(selectUniqueAKeyWords)) {

				for (Map<String, String> map : selectUniqueAKeyWords) {

					String idEncrypt = NumberUtils.idEncrypt(map.get("B000002"));

					map.put("B000002", idEncrypt);

				}
			}

		} else {

			selectUniqueAKeyWords = sSearchDao.selectUniqueCKeyWords(kId, input);

		}

		return selectUniqueAKeyWords != null ? selectUniqueAKeyWords : new ArrayList<Map<String, String>>();
	}

	/**
	 * 
	 *
	 * @Function 通过ES查询关键词
	 * @FileName SSearchServiceImpl.java
	 * @MethodName getKeyWordsByEs
	 * @param kId
	 * @param input
	 * @return
	 * @Date 2018年11月13日 上午11:38:59
	 * @Author Min DongXv
	 *
	 */
	@Override
	public List<Map<String, String>> getKeyWordsByEs(String kId, String input, EsPage page) {
		List<Map<String, String>> selectUniqueAKeyWords = null;
		List<EsQueryEntity> where = new ArrayList<>(1);
		String[] s = null;
		if ("100000".equals(kId)) {
			s = new String[] { "A000001", "A000002" };
		} else if ("100001".equals(kId)) {
			s = new String[] { "B000001", "B000002" };
		} else {
			s = new String[] { "C000001", "C000002" };
		}
		EsQueryEntity e = new EsQueryEntity(EsConstants.SHOULD, s, input);
		where.add(e);
		// EsPage page = new EsPage();
		RestServiceResult<List<Map<String, Object>>> restServiceResult = EsQueryUtil.getList(page,
				EsQueryUtil.whereBuilder(where), null, "doc", EsConstants.INDEX_PREFIX + kId);
		if (RestServiceResult.CODE_SUCCESS == restServiceResult.getCode()) {
			String result = JSON.toJSONString(restServiceResult.getData());
			selectUniqueAKeyWords = JSONObject.parseObject(result, new TypeReference<List<Map<String, String>>>() {
			});
			// 身份证脱敏
			if ("100001".equals(kId) && !CollectionUtils.isEmpty(selectUniqueAKeyWords)) {
				for (Map<String, String> map : selectUniqueAKeyWords) {
					String idEncrypt = NumberUtils.idEncrypt(map.get("B000002"));
					map.put("B000002", idEncrypt);
				}
			}
		}
		return selectUniqueAKeyWords != null ? selectUniqueAKeyWords : new ArrayList<>();
	}

	@Override
	public Map<String, Object> getCollectionStatistics() {

		Map<String, Object> statistics = new HashMap<String, Object>();

		statistics.put("frCollectionNum", 0);
		statistics.put("zrrCollectionNum", 0);
		statistics.put("fqyfrCollectionNum", 0);
		statistics.put("deptNum", 0);
		statistics.put("cubeNum", 0);
		List<Map<String, Object>> collectionStatistics = sSearchDao.selectCollectionStatistics();

		// 信源单位数
		int deptNum = sSearchDao.selectXYDeptCount();

		// 发布使用的公共目录表数量
		int cubeNum = sSearchDao.selectCubeCountFromCommonContentInUse();

		statistics.put("deptNum", deptNum);

		statistics.put("cubeNum", cubeNum);

		if (!CollectionUtils.isEmpty(collectionStatistics)) {

			for (Map<String, Object> unit : collectionStatistics) {

				Object kId = unit.get("kId");

				if ("100000".equals(kId.toString())) {

					statistics.put("frCollectionNum", unit.get("total"));

				} else if ("100001".equals(kId.toString())) {

					statistics.put("zrrCollectionNum", unit.get("total"));

				} else if ("100002".equals(kId.toString())) {

					statistics.put("fqyfrCollectionNum", unit.get("total"));

				}

			}

		}

		return statistics;
	}

	@Override
	public Map<String, Integer> getResourceStatistics(String tybm) {

		Map<String, Integer> map = new HashMap<String, Integer>();
		List<String> tableName = sSearchDao.selectResource(tybm);
		int recordNum = 0;
		if (tableName != null && tableName.size() > 0) {
			recordNum = sSearchDao.selectRecordNum(tableName, tybm);
		}

		int checkNum = creditReportDao.selectCountByTybm(tybm);

		int queriedNum = sSearchDao.selectQueriedNum(tybm);
		map.put("resourceNum", tableName.size());
		map.put("recordNum", recordNum);
		map.put("queriedNum", queriedNum);
		map.put("checkNum", checkNum);
		return map;
	}

	@Override
	public List<Map<String, Object>> getSharingSearchHistoryList(long userId, String kId) {

		return sSearchDao.selectSharingSearchHistoryList(userId, kId);
	}

	@Override
	public Map<String, Object> getUniqueList(Map<String, Object> map) {

		return sSearchDao.selectUniqueList(map);
	}

	@Override
	public void addHistory(String tybm, String kId, long userId) {

		// 检验重复性 tybm + userId
		// 重复更新时间
		// 无则添加
		int updateHistory = sSearchDao.updateHistory(tybm, kId, userId);

		if (updateHistory == 0) {

			sSearchDao.addHistory(tybm, kId, userId);
		}

	}

	@Override
	public List<TableResult> assembleTableComponent(List<TableResult> list) {

		if (!CollectionUtils.isEmpty(list)) {

			Set<String> hitIds = new HashSet<String>();

			// 获取配置样式
			List<ContentStyle> contentStyles = contentStyleService.getByType("XYHC");

			for (TableResult table : list) {

				boolean hit = false;

				StringBuffer sb = new StringBuffer();

				String tableId = table.getTableId();

				String tableShowType = table.getShowType();

				List<DataResult> datas = table.getData();

				// id 匹配的用配置样式 ，否者固定样式
				for (ContentStyle contentStyle : contentStyles) {

					String styleTableId = contentStyle.getTableId();

					if (tableId.equalsIgnoreCase(styleTableId)) {

						hit = true;

						hitIds.add(tableId);

						String tableStyle = contentStyle.getTableStyle();

						if (StringUtils.isNotBlank(tableStyle)) {

							// 有样式单表

							if ("S".equals(tableShowType)) {
								// 有数据
								if (!CollectionUtils.isEmpty(datas)) {

									DataResult dataResult = datas.get(0);

									String addTime = dataResult.getAddTime() == null ? ""
											: dataResult.getAddTime().substring(0, 10);

									List<ColumnResult> columns = dataResult.getColumns();

									org.jsoup.nodes.Document parse = Jsoup.parse(tableStyle);

									sb.append("<h4></h4>");

									for (ColumnResult column : columns) {

										Element element = parse.getElementById(column.getMetricCode());

										if (element != null) {

											element.text(column.getValue() == null ? "" : column.getValue());

										}

									}

									sb.append(parse.getElementsByTag("table").toString());

								} else {
									// 无数据直接返回样式
									sb.append("<div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");
								}

							} else {

								// 有样式多表
								// 有数据
								if (!CollectionUtils.isEmpty(datas)) {

									org.jsoup.nodes.Document parse = Jsoup.parse(tableStyle);

									for (DataResult dataResult : datas) {

										List<ColumnResult> columns = dataResult.getColumns();

										String addTime = dataResult.getAddTime() == null ? ""
												: dataResult.getAddTime().substring(0, 10);

										for (ColumnResult column : columns) {

											String value = column.getValue() == null ? "" : column.getValue();

											Element element = parse.getElementById(column.getMetricCode());

											if (element != null) {

												element.text(value);

											}

										}

										sb.append("<h4></h4>");

										sb.append(parse.getElementsByTag("table").toString());

									}

								} else {

									// 无数据直接返回样式

									sb.append("<div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");

								}

							}

						} else {

							// 默认样式单表

							if ("S".equals(tableShowType)) {

								if (!CollectionUtils.isEmpty(datas)) {

									// 获取最新的一条记录
									DataResult dataResult = datas.get(0);

									List<ColumnResult> columns = dataResult.getColumns();

									String addTime = dataResult.getAddTime() == null ? ""
											: dataResult.getAddTime().substring(0, 10);
									sb.append("<h4></h4>");
									sb.append("<table><tbody>");

									for (ColumnResult columnResult : columns) {

										String metricName = columnResult.getMetricName();

										String value = columnResult.getValue() == null ? "" : columnResult.getValue();

										sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");

									}

									sb.append("</tbody></table>");

								} else {
									// 空数据默认样式返回表头

									sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");

									// List<Column> columns =
									// table.getColumns();
									//
									// for (Column column : columns) {
									//
									// String metricName =
									// column.getMetricName();
									//
									// sb.append("<tr><td>" + metricName +
									// "</td><td></td></tr>");
									//
									// }

									// sb.append("</tbody></table>");

								}

							} else {

								// 默认样式多表

								if (!CollectionUtils.isEmpty(datas)) {

									for (DataResult dataResult : datas) {

										String addTime = dataResult.getAddTime() == null ? ""
												: dataResult.getAddTime().substring(0, 10);

										List<ColumnResult> columns = dataResult.getColumns();

										sb.append("<h4></h4>");
										sb.append("<table><tbody>");

										for (ColumnResult column : columns) {

											String metricName = column.getMetricName();

											String value = column.getValue() == null ? "" : column.getValue();

											sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");

										}

										sb.append("</tbody></table>");

									}

								} else {

									sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");

									// // 空数据默认样式返回表头
									// List<Column> columns =
									// table.getColumns();
									//
									// for (Column column : columns) {
									//
									// String metricName =
									// column.getMetricName();
									//
									// sb.append("<tr><td>" + metricName +
									// "</td><td></td></tr>");
									//
									// }

									// sb.append("</tbody></table>");

								}

							}

						}

						break;
					}

				}

				if (!hit) {

					// 默认样式单表

					if ("S".equals(tableShowType)) {

						if (!CollectionUtils.isEmpty(datas)) {
							sb.append("<table><tbody>");
							// 获取最新的一条记录
							DataResult dataResult = datas.get(0);

							List<ColumnResult> columns = dataResult.getColumns();
							String addTime = dataResult.getAddTime() == null ? ""
									: dataResult.getAddTime().substring(0, 10);
//							sb.append("<h4></h4>");
//							sb.append("<table><tbody>");

							for (ColumnResult columnResult : columns) {

								String metricName = columnResult.getMetricName();

								String value = columnResult.getValue() == null ? "" : columnResult.getValue();
								if (StringUtils.equalsIgnoreCase("基本信息", table.getCategoryName())) {
									sb.append("<tr><td style=\"width: 120px;\">" + metricName + "</td><td>" + value + "</td></tr>");
								} else {
									sb.append("<tr><td>" + metricName + "</td><td>" + value + "</td></tr>");
								}
							}

							sb.append("</tbody></table>");

						} else {

							sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");
							// 空数据默认样式返回表头
							// List<Column> columns = table.getColumns();
							//
							// for (Column column : columns) {
							//
							// String metricName = column.getMetricName();
							//
							// sb.append("<tr><td>" + metricName +
							// "</td><td></td></tr>");
							//
							// }

							// sb.append("</tbody></table>");

						}

					} else {

						// 默认样式多表

						if (!CollectionUtils.isEmpty(datas)) {

							for (DataResult dataResult : datas) {

								String addTime = dataResult.getAddTime() == null ? ""
										: dataResult.getAddTime().substring(0, 10);

								List<ColumnResult> columns = dataResult.getColumns();

								sb.append("<h4></h4>");
								sb.append("<table><tbody>");

								for (ColumnResult column : columns) {

									String metricName = column.getMetricName();

									String value = column.getValue() == null ? "" : column.getValue();

									sb.append("<tr><td style=\"width:120px;\">" + metricName + "</td><td>" + value + "</td></tr>");

								}

								sb.append("</tbody></table>");

							}
						} else {

							sb.append("<div></div><div class='nodata'>截止当前日期，本中心暂未归集到相关信息.</div>");
							// 空数据默认样式返回表头
							// List<Column> columns = table.getColumns();
							//
							// for (Column column : columns) {
							//
							// String metricName = column.getMetricName();
							//
							// sb.append("<tr><td>" + metricName +
							// "</td><td></td></tr>");
							//
							// }

							// sb.append("</tbody></table>");

						}

					}
				}
				table.setTableComponent(sb.toString());
				table.setColumns(null);
				table.setData(null);
			}

		}

		return list;
	}

	@Override
	public List<TableResult> assembleTableComponentForYZS(List<TableResult> list) {

		if (!CollectionUtils.isEmpty(list)) {

			// Set<String> hitIds = new HashSet<String>();

			// 获取配置样式
			List<ContentStyle> contentStyles = contentStyleService.getByType("YZS");

			for (TableResult table : list) {
				boolean hit = false;
				StringBuffer sb = new StringBuffer();

				StringBuffer dataBuffer = new StringBuffer();

				String tableId = table.getTableId();

				String tableShowType = table.getShowType();

				List<DataResult> datas = table.getData();

				// id 匹配的用配置样式 ，否者固定样式
				for (ContentStyle contentStyle : contentStyles) {

					String styleTableId = contentStyle.getTableId();

					if (tableId.equalsIgnoreCase(styleTableId)) {

						hit = true;

						// hitIds.add(tableId);

						String tableStyle = contentStyle.getTableStyle();

						if (StringUtils.isNotBlank(tableStyle)) {

							// 有样式单表

							if ("S".equals(tableShowType)) {
								// 有数据
								if (!CollectionUtils.isEmpty(datas)) {

									DataResult dataResult = datas.get(0);

									String status = dataResult.getStatus();

									List<ColumnResult> columns = dataResult.getColumns();

									org.jsoup.nodes.Document parse = Jsoup.parse(tableStyle);

									for (ColumnResult column : columns) {

										String metricCode = column.getMetricCode();

										Element element = parse.getElementById(metricCode);

										String value = column.getValue();

										if ("B000002".equals(metricCode)) {

											value = NumberUtils.idEncrypt(value);

										}

										if (element != null) {

											element.text(value == null ? "" : value);

										}

									}

									// 关联的修复数据打标签

									if (RecordStatusEnum.FIX.getValue().equals(status)) {

										parse.getElementsByTag("table").addClass("fixed_single");

									}

									sb.append(parse.getElementsByTag("table").toString());

								} else {
									// 无数据直接返回样式
									sb.append(tableStyle);
								}

							} else {

								// 有样式多表
								// 有数据
								if (!CollectionUtils.isEmpty(datas)) {

									org.jsoup.nodes.Document parse = Jsoup.parse(tableStyle);

									Elements metrics = parse.getElementsByAttribute("id");

									if (metrics == null || metrics.size() < 1) {

										throw new ServiceException("【" + table.getTableNameCN() + "】表模板配置有问题,缺少id 配置 ");

									}

									int size = metrics.size();

									for (DataResult dataResult : datas) {

										String status = dataResult.getStatus();

										if (RecordStatusEnum.FIX.getValue().equals(status)) {
											sb.append("<tr class='fixed_multiply'>");
										} else {
											sb.append("<tr>");
										}

										List<ColumnResult> columns = dataResult.getColumns();

										for (int i = 0; i < size; i++) {

											for (ColumnResult column : columns) {

												String text = metrics.get(i).attr("id");

												String metricCode = column.getMetricCode();

												if (metricCode.equals(text)) {

													String value = column.getValue();

													if ("B000002".equals(metricCode)) {

														value = NumberUtils.idEncrypt(value);

													}

													String notNullValue = value == null ? "" : value;

													sb.append("<td><span>" + notNullValue + "</span></td>");

													break;

												}
											}

										}

										sb.append("</tr>");

									}

									parse.getElementsByTag("tbody").append(sb.toString());

									sb.setLength(0);

									sb.append(parse.toString());

								} else {

									// 无数据直接返回样式

									sb.append(tableStyle);

								}

							}

						} else {

							// 默认样式单表

							if ("S".equals(tableShowType)) {

								if (!CollectionUtils.isEmpty(datas)) {

									// 获取最新的一条记录
									DataResult dataResult = datas.get(0);

									String status = dataResult.getStatus();

									if (RecordStatusEnum.FIX.getValue().equals(status)) {
										sb.append("<table class='singleTable fixed_single'><tbody>");
									} else {

										sb.append("<table class='singleTable'><tbody>");
									}

									int i = 0;

									List<ColumnResult> columns = dataResult.getColumns();

									int size = columns.size();

									for (ColumnResult columnResult : columns) {

										String metricName = columnResult.getMetricName();
										String metricCode = columnResult.getMetricCode();

										String value = columnResult.getValue();

										if ("B000002".equals(metricCode)) {

											value = NumberUtils.idEncrypt(value);

										}

										String notNullvalue = value == null ? "" : value;

										if (i % 2 == 0) {

											sb.append("<tr>");

										}

										sb.append("<td>" + metricName + "</td><td>" + notNullvalue + "</td>");

										if (i % 2 != 0 || i == size - 1) {

											sb.append("</tr>");

										}

										i++;

									}

									sb.append("</tbody></table>");

								} else {

									sb.append("<table class='singleTable'><tbody>");
									// 空数据默认样式返回表头
									List<Column> columns = table.getColumns();

									int i = 0;

									int size = columns.size();

									for (Column column : columns) {

										String metricName = column.getMetricName();

										if (i % 2 == 0) {

											sb.append("<tr>");

										}

										sb.append("<td>" + metricName + "</td><td></td>");

										if (i % 2 != 0 || i == size - 1) {

											sb.append("</tr>");

										}

										i++;

									}

									sb.append("</tbody></table>");

								}

							} else {

								sb.append("<table><tbody>");

								// 默认样式多表

								if (!CollectionUtils.isEmpty(datas)) {

									sb.append("<tr>");

									int j = 0;

									for (DataResult dataResult : datas) {

										List<ColumnResult> columns = dataResult.getColumns();

										String status = dataResult.getStatus();

										if (RecordStatusEnum.FIX.getValue().equals(status)) {

											dataBuffer.append("<tr class='fixed_multiply'>");

										} else {

											dataBuffer.append("<tr>");
										}

										for (ColumnResult column : columns) {

											String metricName = column.getMetricName();

											String metricCode = column.getMetricCode();

											String value = column.getValue();

											if ("B000002".equals(metricCode)) {

												value = NumberUtils.idEncrypt(value);

											}

											String notNullValue = value == null ? "" : value;

											dataBuffer.append("<td><span>" + notNullValue + "</span></td>");

											if (j == 0) {

												sb.append("<th>" + metricName + "</th>");

											}
										}

										dataBuffer.append("</tr>");

										j++;

									}

									sb.append("</tr>");

									sb.append(dataBuffer.toString()).append("</tbody></table>");

								} else {
									// 空数据的默认样式返回表头
									List<Column> columns = table.getColumns();
									int size = columns.size();
									sb.append("<tr>");
									for (Column column : columns) {
										sb.append("<th>" + column.getMetricName() + "</th>");
									}

									sb.append("</tr><tr><td style='text-align:center' colspan='" + size
											+ "'>暂无数据</td></tr></tbody></table>");

								}

							}

						}

						break;
					}

				}

				if (!hit) {

					// 默认样式单表

					if ("S".equals(tableShowType)) {

						if (!CollectionUtils.isEmpty(datas)) {

							// 获取最新的一条记录
							DataResult dataResult = datas.get(0);

							String status = dataResult.getStatus();

							if (RecordStatusEnum.FIX.getValue().equals(status)) {
								sb.append("<table class='singleTable fixed_single'><tbody>");
							} else {

								sb.append("<table class='singleTable'><tbody>");
							}

							int i = 0;

							List<ColumnResult> columns = dataResult.getColumns();

							int size = columns.size();

							for (ColumnResult columnResult : columns) {

								String metricName = columnResult.getMetricName();

								String metricCode = columnResult.getMetricCode();

								String value = columnResult.getValue();

								if ("B000002".equals(metricCode)) {

									value = NumberUtils.idEncrypt(value);

								}

								String notNullValue = value == null ? "" : value;

								if (i % 2 == 0) {

									sb.append("<tr>");

								}

								sb.append("<td>" + metricName + "</td><td>" + notNullValue + "</td>");

								if (i % 2 != 0 || i == size - 1) {

									sb.append("</tr>");

								}

								i++;

							}

							sb.append("</tbody></table>");

						} else {

							sb.append("<table class='singleTable'><tbody>");
							// 空数据默认样式返回表头
							List<Column> columns = table.getColumns();

							int i = 0;

							int size = columns.size();

							for (Column column : columns) {

								String metricName = column.getMetricName();

								if (i % 2 == 0) {

									sb.append("<tr>");

								}

								sb.append("<td>" + metricName + "</td><td></td>");

								if (i % 2 != 0 || i == size - 1) {

									sb.append("</tr>");

								}

								i++;

							}

							sb.append("</tbody></table>");

						}

					} else {

						sb.append("<table><tbody>");

						// 默认样式多表

						if (!CollectionUtils.isEmpty(datas)) {

							int j = 0;

							for (DataResult dataResult : datas) {

								List<ColumnResult> columns = dataResult.getColumns();

								String status = dataResult.getStatus();

								if (RecordStatusEnum.FIX.getValue().equals(status)) {

									dataBuffer.append("<tr class='fixed_multiply'>");

								} else {

									dataBuffer.append("<tr>");
								}

								if (j == 0) {
									sb.append("<tr>");
								}

								for (ColumnResult colums : columns) {

									String metricName = colums.getMetricName();

									String metricCode = colums.getMetricCode();

									String value = colums.getValue();

									if ("B000002".equals(metricCode)) {

										value = NumberUtils.idEncrypt(value);

									}

									String notNullValue = value == null ? "" : value;

									dataBuffer.append("<td><span>" + notNullValue + "</span></td>");

									if (j == 0) {

										sb.append("<th>" + metricName + "</th>");

									}
								}

								if (j == 0) {
									sb.append("</tr>");
								}

								dataBuffer.append("</tr>");

								j++;

							}

							sb.append(dataBuffer.toString()).append("</tbody></table>");

						} else {
							// 空数据的默认样式返回表头
							List<Column> columns = table.getColumns();
							int size = columns.size();
							sb.append("<tr>");
							for (Column column : columns) {
								sb.append("<th>" + column.getMetricName() + "</th>");
							}

							sb.append("</tr><tr><td style='text-align:center' colspan='" + size
									+ "'>暂无数据</td></tr></tbody></table>");

						}

					}
				}
				table.setTableComponent(sb.toString().replaceAll(" 00:00:00", ""));
				table.setColumns(null);
				table.setData(null);
			}

		}

		return list;
	}

	@Override
	public String getTYBM(String kId, String searchWord) {
		String tybm = null;

		StringBuilder sb = new StringBuilder();

		if (SubjectTypConstant.SUJECT_TYPE_FR.equals(kId)) {

			sb.append("A000001 = '").append(searchWord).append("' OR ").append("A000002='").append(searchWord)
					.append("'");

		} else if (SubjectTypConstant.SUJECT_TYPE_ZRR.equals(kId)) {

			sb.append("B000001 = '").append(searchWord).append("'");

		} else if (SubjectTypConstant.SUJECT_TYPE_FQYFR.equals(kId)) {

			sb.append("C000001 = '").append(searchWord).append("' OR ").append("C000002='").append(searchWord)
					.append("'");

		}

		if (sb.length() > 0)

		{
			tybm = sSearchDao.selectTybm(kId, sb.toString());
		}
		return tybm;
	}

	@Override
	public List<Map<String, String>> getSubjectLsitForPage(String kId, String input, Page page) {

		String whereSql = null;

		List<Map<String, String>> list = new ArrayList<>();

		if (SubjectTypConstant.SUJECT_TYPE_FR.equals(kId)) {

			whereSql = " select a.* from t_zoo_subject_unique_100000 a   where  a.A000001 LIKE '" + input + "%' OR a.A000002 = '" + input + "'";

		} else if (SubjectTypConstant.SUJECT_TYPE_ZRR.equals(kId)) {

			whereSql = " select a.* from t_zoo_subject_unique_100001 a    where a.B000001 LIKE '" + input + "%' OR a.B000002 = '" + input + "'";

		} else if (SubjectTypConstant.SUJECT_TYPE_FQYFR.equals(kId)) {

			whereSql = "select a.* from t_zoo_subject_unique_100002 a  where  a.C000001 LIKE '" + input + "%' OR a.C000002 = '" + input + "'";
		}

		if (whereSql != null) {

			list = sSearchDao.selectUniqueByKeyForPage(kId, whereSql, page);

			if (!CollectionUtils.isEmpty(list) && SubjectTypConstant.SUJECT_TYPE_ZRR.equals(kId)) {

				for (Map<String, String> map : list) {

					String idEncrypt = NumberUtils.idEncrypt(map.get("B000002"));

					map.put("B000002", idEncrypt);

				}
			}

		}

		return list;
	}

	
	@Override
	public Map<String,Object> assembleTableComponentForMHWZ(List<TableResult> list,String tybm) {
		
		Map<String,Integer> map = new HashMap<>();
		Set<String> categorySet = new HashSet<String>();
		int count = 0;
		for(int i=0;i<list.size();i++) {
			String categoryName = list.get(i).getCategoryName();	
		
			if(!categorySet.contains(categoryName)) {
				categorySet.add(categoryName);
		}
		}
		//获取所有类
		List<String> lists = new ArrayList<>(categorySet);
		//将所有类转Map<Object,List<>>
		  Map<Object, List<Object>> maps = lists.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.toList()));
		 for(String key :lists) {
			 //生成的map中key对应的value值清除
			 maps.get(key).clear();
		 }
		 Map<String,Object> map1 =  new HashMap<String,Object>();	
		 if (!CollectionUtils.isEmpty(list)) {			
			for (TableResult table : list) {	
				List<DataResult> datas = table.getData();
				String tablename = "t_"+table.getTableNameEN();
				String type = table.getCategoryName();	
				for(Object key:maps.keySet()) {
					if(type.equals(key)) {
						//行政处罚判断公示截至日期
						if(tablename.endsWith("t_1000000010002_XSni4zSzP0")) {
							//获取对应表的数据
							List<Object> datalist = sSearchDao.getXzcfList(tablename,tybm);	
							//二级类map
							map1.put(table.getTableNameCN(), datalist);
							map1.put("size", datalist.size());
							maps.get(key).add(map1);					
							map1 = new HashMap<String,Object>();	
						}else if(tablename.endsWith("t_1000000010001_3ioj4GeZQU")) {
							//获取对应表的数据
							List<Object> datalist = sSearchDao.getXzXkList(tablename,tybm);	
							//二级类map
							map1.put(table.getTableNameCN(), datalist);
							map1.put("size", datalist.size());
							maps.get(key).add(map1);					
							map1 = new HashMap<String,Object>();	
						}else{
							//获取对应表的数据
							List<Object> datalist = sSearchDao.getDataList(tablename,tybm);	
							//二级类map
							map1.put(table.getTableNameCN(), datalist);
							map1.put("size", datalist.size());
							maps.get(key).add(map1);					
							map1 = new HashMap<String,Object>();	
						}				
						
					}
				}	
		}
		}
		Map<String,Object> result = new HashMap<>();		
		for(String key :lists) {
			result.put(key, maps.get(key));
		}		
		return result;
	}

	@Override
	public Map<String, Integer> selectInfoDetailLog(String qymc, String tybm) {
		
		return sSearchDao.selectInfoDetailLog(qymc,tybm);
	}

	@Override
	public void updateInfoDetailLog(String qymc, String tybm) {
		sSearchDao.updateInfoDetailLog(qymc,tybm);
		
	}

	@Override
	public void addInfoDetailLog(String qymc, String tybm) {
		sSearchDao.addInfoDetailLog(qymc,tybm);
		
	}

	@Override
	public Map<String, Object> xyhcassembleTableComponentForMHWZ(List<TableResult> list, String qymc,String tybm) {
		Map<String,Integer> map = new HashMap<>();
		Set<String> categorySet = new HashSet<String>();
		int count = 0;
		for(int i=0;i<list.size();i++) {
			String categoryName = list.get(i).getCategoryName();	
		
			if(!categorySet.contains(categoryName)) {
				categorySet.add(categoryName);
		}
		}
		//获取所有类
		List<String> lists = new ArrayList<>(categorySet);
		//将所有类转Map<Object,List<>>
		  Map<Object, List<Object>> maps = lists.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.toList()));
		 for(String key :lists) {
			 //生成的map中key对应的value值清除
			 maps.get(key).clear();
		 }
		 Map<String,Object> map1 =  new HashMap<String,Object>();	
		 if (!CollectionUtils.isEmpty(list)) {			
			for (TableResult table : list) {	
				List<DataResult> datas = table.getData();
				String tablename = "t_"+table.getTableNameEN();
				String type = table.getCategoryName();	
				for(Object key:maps.keySet()) {
					if(type.equals(key)) {
						//行政处罚判断公示截至日期
						if(tablename.endsWith("t_1000000010002_XSni4zSzP0")) {
							//获取对应表的数据
							List<Object> datalist = sSearchDao.getXzcfList(tablename,tybm);	
							//二级类map
							map1.put(table.getTableNameCN(), datalist);
							map1.put("size", datalist.size());
							maps.get(key).add(map1);					
							map1 = new HashMap<String,Object>();	
						}else if(tablename.endsWith("t_1000000010001_3ioj4GeZQU")) {
							//获取对应表的数据
							List<Object> datalist = sSearchDao.getXzXkList(tablename,tybm);	
							//二级类map
							map1.put(table.getTableNameCN(), datalist);
							map1.put("size", datalist.size());
							maps.get(key).add(map1);					
							map1 = new HashMap<String,Object>();	
						}else{
							//获取对应表的数据
							List<Object> datalist = sSearchDao.getDataList(tablename,tybm);	
							//二级类map
							map1.put(table.getTableNameCN(), datalist);
							map1.put("size", datalist.size());
							maps.get(key).add(map1);					
							map1 = new HashMap<String,Object>();	
						}				
																							
					}
				}	
		}
		}
		Map<String,Object> result = new HashMap<>();		
		for(String key :lists) {
			result.put(key, maps.get(key));
		}		
		return result;
	}
}
